package com.ggy.babybed.util;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by ggy on 2016/7/7.
 */
public class SecurityUtil {

    /** 加密算法 */
    private String Algorithm = "DES";
    /** 默认的key:交换算子必须8位 */
    private String defaultKey = "babyskey";
    private SecretKey deskey;
    private Cipher cipher;

    public SecurityUtil() {
        init(defaultKey);
    }

    public SecurityUtil(String key) {
        this.defaultKey = key;
        init(defaultKey);
    }

    /**
     * 初始化 DES 加密算法的一些参数
     */
    private void init(String key) {
        try {
            byte bKey[] = key.getBytes();
            deskey = new SecretKeySpec(bKey, Algorithm);
            cipher = Cipher.getInstance(Algorithm);
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 对 datasource 数组进行解密
     * @param datasource 要解密的数据
     * @return 返回加密后的 byte[]
     */
    public byte[] createDecryptor(byte[] datasource) {
        byte[] decryptorData = null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, deskey);
            decryptorData = cipher.doFinal(datasource);
        } catch (java.security.InvalidKeyException ex) {
            return new byte[] {};
        } catch (javax.crypto.BadPaddingException ex) {
            return new byte[] {};
        } catch (javax.crypto.IllegalBlockSizeException ex) {
            return new byte[] {};
        }
        return decryptorData;
    }

    /**
     * 对 byte[] 进行加密
     * @param datasource 要加密的数据
     * @return 返回加密后的 byte 数组
     */
    public byte[] createEncryptor(byte[] datasource) {
        /** 解密数据 */
        byte[] encryptorData = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, deskey);
            encryptorData = cipher.doFinal(datasource);
        } catch (java.security.InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (javax.crypto.BadPaddingException ex) {
            ex.printStackTrace();
        } catch (javax.crypto.IllegalBlockSizeException ex) {
            ex.printStackTrace();
        }
        return encryptorData;
    }

    /**
     * 将字符串加密
     * @param datasource
     * @return
     * @throws Exception
     */
    public byte[] createEncryptor(String datasource) throws Exception {
        return createEncryptor(datasource.getBytes("UTF-8"));
    }

}
